package templates

import "github.com/spf13/cobra"

// 给子命令分组，形成 CommandGroups 结构，方便输出清晰的 usage 信息

type CommandGroup struct {
	Message  string
	Commands []*cobra.Command
}

type CommandGroups []CommandGroup

// 把 g 中的所有命令全部加载到 c 上作为子命令
func (g CommandGroups) AddTo(c *cobra.Command) {
	for _, group := range g {
		c.AddCommand(group.Commands...)
	}
}

// g 中是否包含命令 c
func (g CommandGroups) Has(c *cobra.Command) bool {
	for _, group := range g {
		for _, command := range group.Commands {
			if command == c {
				return true
			}
		}
	}
	return false
}

// 往 g 中添加新的命令组，新组中的命令是与 g 中原有命令去重后剩下的
func AddAdditionalCommands(g CommandGroups, message string, cmds []*cobra.Command) CommandGroups {
	group := CommandGroup{Message: message}
	for _, c := range cmds {
		// Don't show commands that have no short description
		if !g.Has(c) && len(c.Short) != 0 {
			group.Commands = append(group.Commands, c)
		}
	}
	if len(group.Commands) == 0 {
		return g
	}
	return append(g, group)
}
